package com.baor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baor.config.RedisUtil;
import com.baor.config.TokenService;
import com.baor.dao.RoleDao;
import com.baor.dao.UserDao;
import com.baor.dao.UserRoleDao;
import com.baor.domain.*;
import com.baor.service.UserService;
import com.baor.util.MD5Util;
import com.baor.util.R;
import com.baor.util.UploadUtil;

import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private UploadUtil uploadUtil;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    //user 参数  account + password
    public R login(UserVO user) {
        user.setPassword(MD5Util.md5(user.getPassword()));
        //数据库查询返回的对象
        UserVO userInfo = userDao.selectOne(new LambdaQueryWrapper<UserVO>()
                .eq(UserVO::getUsername, user.getUsername())
                .eq(UserVO::getPassword, user.getPassword()));
        System.out.println(userInfo);

        if (userInfo != null) {
            if(redisUtil.getValue("token"+userInfo.getId()) != null) {
                Object token = redisUtil.getValue("token"+userInfo.getId());
                Map<String, Object> res = new HashMap<>();
                res.put("token", token);
                res.put("user", userInfo);

                return R.ok(res);

            }else{
                Object token = tokenService.createToken(userInfo);
                redisUtil.setValue("token"+userInfo.getId(), token);
                Map<String, Object> res = new HashMap<>();
                res.put("token", token);
                res.put("user", userInfo);
                return R.ok(res);
            }

        }else{
            return R.er();
        }


    }
    @Override
    @Transactional
    public R insertUser(UserVO user) {
        if(user.getPassword() == user.getApassword()){
            return R.er("两次密码不一致");
        }
        if(user.getRoleId() == null){
            return R.er("用户组");
        }
        if(user.getPassword() != null || user.getApassword()!=null || user.getPassword() == user.getApassword()) {
            user.setPassword(MD5Util.md5(user.getPassword()));
            int roleId = user.getRoleId();
            int row = this.userDao.insert(user);
            if(row > 0){
                Integer userId = user.getId();
                Map<String, Object> params = new HashMap<>();
                params.put("userId", userId);
                params.put("roleId", roleId);
                this.userRoleDao.insertUserRole(params);
            }




            return row > 0 ? R.ok() : R.er();
        }
       return R.er("密码不能是空");

    }

    @Override
    public R updateUser(UserVO user) {
        System.out.println(user.getPassword()+user.getApassword());
        if (user.getPassword() != null && user.getApassword() != null
                && user.getPassword().equals(user.getApassword())) {
            user.setPassword(MD5Util.md5(user.getPassword()));
        } else {
            return R.er("两次密码不一致");
        }
        if(user.getRoleId() == null){
            return R.er("用户组id不存在或为空");
        }
        if(user.getPhone()!= null){
            user.setPhone(user.getPhone());
        }
        if(user.getStatus()!= null){
            user.setStatus(user.getStatus());
        }
        if(user.getRemark()!= null){
            user.setRemark(user.getRemark());
        }
        this.userDao.updateById(user);
        int userId = user.getId();
        if(user.getRoleId() != null){
            this.userRoleDao.deleteUserRole(userId);
            int roleId = user.getRoleId();
            Map<String, Object> params = new HashMap<>();
            params.put("roleId", roleId);
            params.put("userId", userId);
            int row = this.userRoleDao.insertUserRole(params);
            return row > 0 ? R.ok() : R.er();
        }


        return R.er();

    }


    @Override
    public R uploadIcon(MultipartFile[] files) {
        return R.ok(this.uploadUtil.uploadUtil("/icon",files));
    }

    @Override
    public R userList(Map<String, Object> params) {

        MPJLambdaWrapper<UserVO> wrapper = new MPJLambdaWrapper<UserVO>()
                .select(UserVO::getId)
                .select(UserVO::getUsername)
                .select(UserVO::getPhone)
                .select(UserVO::getRegistertime)
                .select(UserVO::getStatus)
                .select(UserVO::getRemark)
                .selectAs(RoleVo::getName, UserVO::getRoleName)
                .leftJoin(UserRoleVo.class, UserRoleVo::getUserId, UserVO::getId)
                .leftJoin(RoleVo.class, RoleVo::getId, UserRoleVo::getRoleId);


        wrapper.eq(UserVO::getIsDeleted,0);
        System.out.println(params);
        Page page = new Page();
        page.setCurrent((Integer) params.get("pageIndex"));
        page.setSize((Integer) params.get("pageSize"));
        IPage<UserVO> iPage = this.userDao.selectPage(page, wrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("totalSize", iPage.getTotal());
        map.put("List", iPage.getRecords());

        return R.ok(map);

    }


}
